#include "global.h"

#define SQUARE_WAVE			0x36

#define TIMER_FREQUENCY		1193182L
#define TIMER_TICK			(TIMER_FREQUENCY / 60)
#define TIMER_MODE			0x43
#define TIMER0				0x40
#define TIMER_IRQ			0x00

#define CONTROL_REGISTER	0x20
#define INTERRUPT_MASK		0x21

int tick, seconds, minutes, hours;

void enable_irq(int irq_nr)
{
	int value = read_port(INTERRUPT_MASK);
	value &= ~(1 << irq_nr);
	write_port(INTERRUPT_MASK, value);
}

void timerHandler();
void initializeTimer()
{
	printf("  * Initializing system timer... ");
	
	// Initialize the wall clock to 0
	tick = seconds = minutes = hours = 0;
	
	// Install the interrupt handler
	putWord((int)thandler, 0x0, 32);
	putWord(0x1000, 0x0, 34);
	
	// Setup the timer to run
	write_port(TIMER_MODE, SQUARE_WAVE);
	write_port(TIMER0, TIMER_TICK);
	write_port(TIMER0, TIMER_TICK >> 8);
	enable_irq(TIMER_IRQ);
	
	printf("Done!\n");
}

void timerHandler()
{
	++tick;
	tick %= 60;
	
	if (tick == 0)
	{
		++seconds;
		minutes = seconds / 60;
		hours = minutes / 60;
		writeSystemTime(seconds % 60, minutes % 60, hours % 24);
	}
	
	// Decrement the running processes time if we're not in kmode
	if (inkmode == 1)
	{
		--running->time;
		if (running->time <= 0)
		{
			write_port(0x20, 0x20);
			tswitch();
		}
	}
	
	write_port(0x20, 0x20);
}
